const router = require("koa-router")();
const {
  isExist,
  register,
  login,
  deleteCurUser,
  changeUserInfo,
  changePassword,
  logout,
} = require("../../controller/user");
const userValidate = require("../../validator/user");
const { genValidator } = require("../../middlewares/validator");
const { loginCheck } = require("../../middlewares/loginChecks");

router.prefix("/api/user");

//注册用户
router.post("/register", genValidator(userValidate), async (ctx, next) => {
  const { userName, password, gender } = ctx.request.body;
  ctx.body = await register({
    userName,
    password,
    gender,
  });
});

//判断用户是否存在
router.post("/isExist", async (ctx, next) => {
  const { userName } = ctx.request.body;
  ctx.body = await isExist(userName);
});

//用户登录
router.post("/login", async (ctx, next) => {
  const { userName, password } = ctx.request.body;
  ctx.body = await login(ctx, userName, password);
});

//用户删除
router.post("/delete", loginCheck, async (ctx, next) => {
  ctx.body = await deleteCurUser(ctx);
});

//用户信息修改
router.patch(
  "/changeInfo",
  genValidator(userValidate),
  loginCheck,
  async (ctx, next) => {
    const { nickName, city, picture } = ctx.request.body;
    ctx.body = await changeUserInfo(ctx, {
      nickName,
      city,
      picture,
    });
  }
);

//用户密码修改
router.patch("/changePassword", loginCheck, async (ctx, next) => {
  const { password, newPassword } = ctx.request.body;
  ctx.body = await changePassword(ctx, password, newPassword);
});

//退出登录
router.post("/logout", loginCheck, async (ctx, next) => {
  ctx.body = await logout(ctx);
});

module.exports = router;
